class PageSlider {
    constructor() {
        console.log('Initializing PageSlider');
        
        // 获取元素
        this.container = document.getElementById('slideContainer');
        this.content = document.getElementById('slideContent');
        
        if (!this.container || !this.content) {
            console.error('Required elements not found');
            return;
        }
        
        // 初始化变量
        this.startX = 0;
        this.startY = 0;
        this.currentX = 0;
        this.currentY = 0;
        this.isDragging = false;
        this.isScrolling = null;
        this.touchStartTime = 0;
        
        // 配置参数
        this.minSwipeDistance = 50; // 最小滑动距离
        this.maxSwipeTime = 300; // 最大滑动时间（毫秒）
        this.scrollThreshold = 10; // 滚动判定阈值
        
        // 绑定事件处理器
        this.handleTouchStart = this.handleTouchStart.bind(this);
        this.handleTouchMove = this.handleTouchMove.bind(this);
        this.handleTouchEnd = this.handleTouchEnd.bind(this);
        this.handleMouseDown = this.handleMouseDown.bind(this);
        this.handleMouseMove = this.handleMouseMove.bind(this);
        this.handleMouseUp = this.handleMouseUp.bind(this);
        
        this.initEventListeners();
        console.log('PageSlider initialized successfully');
    }

    initEventListeners() {
        // 触摸事件
        this.container.addEventListener('touchstart', this.handleTouchStart, { passive: true });
        this.container.addEventListener('touchmove', this.handleTouchMove, { passive: false });
        this.container.addEventListener('touchend', this.handleTouchEnd);

        // 鼠标事件
        this.container.addEventListener('mousedown', this.handleMouseDown);
        window.addEventListener('mousemove', this.handleMouseMove);
        window.addEventListener('mouseup', this.handleMouseUp);
    }

    handleTouchStart(e) {
        const touch = e.touches[0];
        this.startX = touch.clientX;
        this.startY = touch.clientY;
        this.touchStartTime = Date.now();
        this.isScrolling = null;
        this.content.style.transition = 'none';
        console.log('Touch Start:', { x: this.startX, y: this.startY });
    }

    handleTouchMove(e) {
        if (e.touches.length > 1) return;

        const touch = e.touches[0];
        const deltaX = touch.clientX - this.startX;
        const deltaY = touch.clientY - this.startY;

        // 检查是否在滚动容器内
        const tableContainer = e.target.closest('.table-scroll-container');
        if (tableContainer) {
            // 如果在滚动容器内且主要是垂直移动，允许滚动
            if (Math.abs(deltaY) > Math.abs(deltaX)) {
                return;
            }
        }

        // 首次移动时判断方向
        if (this.isScrolling === null) {
            this.isScrolling = Math.abs(deltaY) > Math.abs(deltaX);
            console.log('Determined direction:', this.isScrolling ? 'vertical' : 'horizontal');
        }

        if (this.isScrolling) {
            return;
        } else {
            e.preventDefault();
            this.currentX = deltaX;
            this.applyTransform(this.currentX);
            console.log('Horizontal move:', deltaX);
        }
    }

    handleTouchEnd(e) {
        if (this.isScrolling) return;

        const swipeTime = Date.now() - this.touchStartTime;
        console.log('Swipe time:', swipeTime);

        if (swipeTime < this.maxSwipeTime && Math.abs(this.currentX) > this.minSwipeDistance) {
            this.handleSwipe();
        } else {
            this.bounceBack();
        }
    }

    handleMouseDown(e) {
        e.preventDefault();
        this.isDragging = true;
        this.startX = e.clientX;
        this.startY = e.clientY;
        this.touchStartTime = Date.now();
        this.content.style.transition = 'none';
        this.content.style.cursor = 'grabbing';
        console.log('Mouse Down:', { x: this.startX, y: this.startY });
    }

    handleMouseMove(e) {
        if (!this.isDragging) return;

        const deltaX = e.clientX - this.startX;
        const deltaY = e.clientY - this.startY;

        // 判断是否为水平移动
        if (Math.abs(deltaX) > Math.abs(deltaY)) {
            e.preventDefault();
            this.currentX = deltaX;
            this.applyTransform(this.currentX);
            console.log('Mouse move:', deltaX);
        }
    }

    handleMouseUp(e) {
        if (!this.isDragging) return;
        
        this.isDragging = false;
        const swipeTime = Date.now() - this.touchStartTime;
        this.content.style.cursor = '';

        if (swipeTime < this.maxSwipeTime && Math.abs(this.currentX) > this.minSwipeDistance) {
            this.handleSwipe();
        } else {
            this.bounceBack();
        }
    }

    applyTransform(x) {
        requestAnimationFrame(() => {
            this.content.style.transform = `translateX(${x}px)`;
        });
    }

    handleSwipe() {
        this.content.style.transition = 'transform 0.3s ease-out';
        const direction = this.currentX > 0 ? 'right' : 'left';
        this.navigatePage(direction);
    }

    bounceBack() {
        this.content.style.transition = 'transform 0.3s ease-out';
        this.applyTransform(0);
    }

    navigatePage(direction) {
        const currentPath = window.location.pathname;
        const reportUuid = currentPath.match(/\/reports\/([^\/]+)/)?.[1];
        if (!reportUuid) return;

        let nextPath;
        if (direction === 'right') {
            if (currentPath.includes('top-requests')) nextPath = `/reports/${reportUuid}`;
            else if (currentPath.includes('inspection-stats')) nextPath = `/reports/${reportUuid}/top-requests`;
            else if (currentPath.includes('thanks')) nextPath = `/reports/${reportUuid}/inspection-stats`;
        } else {
            if (currentPath === `/reports/${reportUuid}`) nextPath = `/reports/${reportUuid}/top-requests`;
            else if (currentPath.includes('top-requests')) nextPath = `/reports/${reportUuid}/inspection-stats`;
            else if (currentPath.includes('inspection-stats')) nextPath = `/reports/${reportUuid}/thanks`;
        }

        if (nextPath) {
            console.log('Navigating to:', nextPath);
            window.location.href = nextPath;
        } else {
            this.bounceBack();
        }
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM Content Loaded');
    new PageSlider();
});

// 错误处理
window.addEventListener('error', (e) => {
    console.error('JavaScript Error:', e.message);
}); 